Qt.include("sha1.js")
Qt.include("oauth.js")

var oauth_data = { }

oauth_data.oauth_realm = ""
oauth_data.consumer_key = "";
oauth_data.consumer_secret = "";
oauth_data.request_token_url = "";
oauth_data.authorize_token_url = "";
oauth_data.access_token_url = "";
oauth_data.callback_url = "";
oauth_data.oauth_token = "";
oauth_data.oauth_token_secret = "";
oauth_data.request_token_method = "GET" // POST
oauth_data.access_token_method = "GET" // POST
oauth_data.auth_method = "URL"  // HEADER


function requestToken() {
    var url = oauth_data.request_token_url;

    var accessor = {
      consumerKey : oauth_data.consumer_key,
      consumerSecret: oauth_data.consumer_secret
    };

    var message = {
      action: url,
      method: oauth_data.request_token_method,
      parameters: {
        oauth_callback: oauth_data.callback_url
      }
    };

    OAuth.completeRequest(message, accessor);
//    OAuth.SignatureMethod.sign(message, accessor);
    if(oauth_data.auth_method == "URL") {
        url = OAuth.addToURlog(url, message.parameters);
    }

    log(url);

    var doc = new XMLHttpRequest();
    doc.onreadystatechange = function() {
         if (doc.readyState == XMLHttpRequest.DONE) {
             if(doc.status === 200) {
                 log("RESPONSE: " + doc.responseText);

                 log(doc.getResponseHeader("x-opensocial-error"))

                 var list = OAuth.decodeForm(doc.responseText);

                 oauth_data.oauth_token = list[0][1];
                 oauth_data.oauth_token_secret = list[1][1];
                 //var oauth_callback_confirmed = list[2][1];

                 log(oauth_data.oauth_token);
                 log(oauth_data.oauth_token_secret);

                 var authorizeUrl = oauth_data.authorize_token_url + "?oauth_token=" + oauth_data.oauth_token + "&oauth_callback=" + oauth_data.callback_url;
                 window.currentScreen.requestTokenReady(authorizeUrl);
             } else {
                 log("Error getting request token!");
                 log("RESPONSE: " + doc.status);
                 log("RESPONSE: " + doc.statusText);
                 log("RESPONSE: " + doc.getAllResponseHeaders());

             }
         }
     }

     doc.open(oauth_data.request_token_method, url);

     if (oauth_data.auth_method == "HEADER") {
            var header = OAuth.getAuthorizationHeader(oauth_data.oauth_realm, message.parameters);
//            header = header.replace('realm="",', " ");
         log("header: " + header);
            doc.setRequestHeader("Authorization", header);
     }

     doc.send();

}

function getAccessToken(verifier) {
    var url = oauth_data.access_token_url;
    var accessor = {
      token: oauth_data.oauth_token,
      tokenSecret: oauth_data.oauth_token_secret,
      consumerKey : oauth_data.consumer_key,
      consumerSecret: oauth_data.consumer_secret
    };

    var message = {
      action: url,
      method: oauth_data.access_token_method,
      parameters: {
        oauth_verifier: verifier
      }
    };

    OAuth.completeRequest(message, accessor);
//    OAuth.SignatureMethod.sign(message, accessor);
    if(oauth_data.auth_method == "URL") {
        url = OAuth.addToURL(url, message.parameters);
    }
    log(url);

    var doc = new XMLHttpRequest();
    doc.onreadystatechange = function() {
        log(doc.readyState);

         if (doc.readyState == XMLHttpRequest.DONE) {
             if(doc.status == 200) {
                 // successfull
                 var list = OAuth.decodeForm(doc.responseText);
                 log("RESPONSE: " + doc.responseText);
                 oauth_data.oauth_token = list[0][1];
                 oauth_data.oauth_token_secret = list[1][1];

                 saveAuthInfo(oauth_data.oauth_realm, oauth_data.oauth_token, oauth_data.oauth_token_secret);

                 log("TOKEN: " + oauth_data.oauth_token);
                 log("TOKEN SECRET: " + oauth_data.oauth_token_secret);
                 window.currentScreen.accessTokenReady(oauth_data.oauth_token, oauth_data.oauth_token_secret);
             } else {
                // error
                 log("Error getting access token!");
                 log("RESPONSE: " + doc.status);
                 log("RESPONSE: " + doc.statusText);
                 log("RESPONSE: " + doc.getAllResponseHeaders());
             }
         }
     }

     doc.open(oauth_data.access_token_method, url);
     if (oauth_data.auth_method == "HEADER") {
        var header = OAuth.getAuthorizationHeader(oauth_data.oauth_realm, message.parameters);
        doc.setRequestHeader("Authorization", header);
     }
     doc.send();
}

// oauth_token=mb1wwVEnSp969WCkv9IbNw&oauth_token_secret=JwG6w5eiQEBAL2qL8dds8tDDHQzswwbBl54i7sASZE&user_id=miso1

function signURL(method, url, params) {
    if(oauth_data.oauth_token == "" && oauth_data.oauth_token_secret == "")
        loadAuthInfo(oauth_data.oauth_realm);

    var accessor = {
      token: oauth_data.oauth_token,
      tokenSecret: oauth_data.oauth_token_secret,
      consumerKey : oauth_data.consumer_key,
      consumerSecret: oauth_data.consumer_secret
    };

    var message = {
      action: url,
      method: method,
      parameters: params
    };

    OAuth.completeRequest(message, accessor);
    OAuth.SignatureMethod.sign(message, accessor);
    url = url + '?' + OAuth.formEncode(message.parameters);
    log(url);
    return url;
}

function signUrl(requestUrl, params) {
    return signURL("GET", requestUrl, params);
}

function signPostUrl(requestUrl, params) {
    return signURL("POST", requestUrl, params);
}

function signPutUrl(requestUrl, params) {
    return signURL("PUT", requestUrl, params);
}

function loadAuthInfo(realm) {
    var db = openDatabaseSync("MySpaceLocalDB", "1.0", "MySpace QML Storage", 1024);
    var loggedIn = false;

    db.transaction(
        function(tx) {
//            tx.executeSql("DROP TABLE auth_info");
            tx.executeSql("CREATE TABLE IF NOT EXISTS auth_info (realm TEXT, token TEXT, token_secret TEXT)");
            var rs = tx.executeSql("SELECT token, token_secret FROM auth_info WHERE realm = ?", realm);
            if(rs.rows.length > 0) {
                oauth_data.oauth_token = rs.rows.item(0).token;
//                log("LOADING TOKEN" + oauth_token);
                oauth_data.oauth_token_secret = rs.rows.item(0).token_secret;
//                log("LOADING SECRET" + oauth_token_secret);
                log("LOADING TOKEN: " + oauth_data.oauth_token);
                log("LOADING SECRET: " + oauth_data.oauth_token_secret);
                loggedIn = true;
            }
        }
    );

    return loggedIn;
}

function saveAuthInfo(realm, token, token_secret) {
    var db = openDatabaseSync("MySpaceLocalDB", "1.0", "MySpace QML Storage", 1024);

    db.transaction(
        function(tx) {
//            tx.executeSql("DROP TABLE auth_info");
            tx.executeSql("CREATE TABLE IF NOT EXISTS auth_info (realm TEXT, token TEXT, token_secret TEXT)");
            tx.executeSql("DELETE FROM auth_info WHERE realm = ?", realm);
            tx.executeSql("INSERT INTO auth_info VALUES (?,?,?)", [realm, token, token_secret]);
        }

    );
}

function clearAuthInfo() {
    var db = openDatabaseSync("MySpaceLocalDB", "1.0", "MySpace QML Storage", 1024);

    db.transaction(
        function(tx) {
            tx.executeSql("DELETE FROM auth_info WHERE realm = ?", oauth_data.oauth_realm);
        }
    );
}

function getAuthHeader() {
    return OAuth.getAuthorizationHeader();
}
